import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';
import { t } from '@lingui/macro';

export default class LineTimeStore {
  _args = {
    search: {},
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  data = [];
  companyData = [];
  loading = false;

  shiftInfo= {};

  fromCity = '';
  toCity = '';
  startStation = '';
  endStation = '';

  _lineStatus = '2'

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  get api() {
    return api;
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    search.type = Number(this._lineStatus);
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      const prices = yield api.search({ search, pg });
      this.data = prices;
    } finally {
      this.loading = false;
    }
  }

  * get(id) {
    const res = yield api.get(id);
    return observable(res);
  }

  * _reload() {
    yield this.query();
  }

  * update(price) {
    yield api.update({ ...price });
    yield this._reload(price);
  }

  * create(price) {
    yield api.create({ ...price });
    yield this._reload(price);
  }

  * remove(price) {
    yield api.remove(price.id);
    yield this._reload(price);
  }

  * updateState(price) {
    // eslint-disable-next-line no-param-reassign
    price.state = price.state === '0' ? '1' : '0';
    yield api.update(price);
    yield this.query();
  }

  * getCompany(args) {
    const res = yield api.getCompany(args);
    return res.map((item) => ({
      label: item.name,
      value: item.id,
    }));
  }

  * getShifts(args) {
    const res = yield api.getShifts(args);
    return res;
  }

  async exitingLines(price) {
    const {
      priceType,
      startMainArea,
      endMainArea,
      startMinorAreas,
      endMinorAreas,
      portTypes: ports,
    } = toJS(price);
    return api.existingLines({
      priceType,
      startMainArea,
      endMainArea,
      startMinorAreas,
      endMinorAreas,
      ports,
      excludeId: price.id,
    });
  }

  async existsValidator(rule, value) {
    if (!value) return Promise.resolve();
    try {
      const item = await api.get(value); // 注意get不存在时会抛出404异常
      if (item) return Promise.reject(new Error(t`${value}已存在`));
    } catch (_) {
      return Promise.resolve();
    }
  }

  * getBusCity(args) {
    const res = yield api.getBusCity(args);
    const mapRes = res.map((item) => ({
      label: item.name,
      value: item.itemId,
    }));
    return mapRes;
  }

  * getBusStation(args) {
    const station = yield api.getBusStation(args);
    // eslint-disable-next-line @iceworks/best-practices/recommend-polyfill
    const stationMap = station.flatMap((item) => item.children.map((innerItem) => ({
      label: innerItem.name,
      value: innerItem.id,
      title: innerItem.name,
    })));
    return stationMap;
  }

  * getScCity(data) {
    const station = yield api.getScCity(data);
    const stationMap = station.map((item) => ({
      label: item.name,
      value: item.itemId,
    }));
    return stationMap;
  }

  * getScStation(data) {
    const station = yield api.getScStation(data);
    const temp = station.reduce((acc, arr) => {
      return acc.concat(arr.children);
    }, []);
    const stationMap = temp.map((item) => ({
      label: item.name,
      value: item.id,
    }));
    return stationMap;
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
    // _.mergeWith(this._args.pg, pg, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get lineStatus() {
    return this._lineStatus;
  }

  set lineStatus(value) {
    this._lineStatus = value;
    this._args.pg.page = 0;
    this.query({ page: 0 });
  }
}
